package com.mydroidchat.controllers;

import com.mydroidchat.data.ChatMessage;
import com.mydroidchat.data.net.MessageResponse;
import com.mydroidchat.data.net.MessagesRequest;
import com.mydroidchat.views.ChatPanelView;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;

public class ChatPanelController extends Controller {
    private Set<ChatMessage> chatMessages;
    private ChatPanelView panelView;
    private final Thread thread = new Thread(new Runnable() {
        public void run() {
            while (true) {
                MessageResponse response = new MessagesRequest().execute();
                Set<ChatMessage> messages = response.getMessages();
                ArrayList<ChatMessage> clone = new ArrayList<ChatMessage>(messages);
                clone.removeAll(chatMessages);
                if (clone.size() > 0) {
                    chatMessages.addAll(messages);
                    ArrayList<ChatMessage> list = new ArrayList<ChatMessage>(chatMessages);
                    Collections.sort(list, new Comparator<ChatMessage>() {
                        public int compare(ChatMessage o1, ChatMessage o2) {
                            return (int) (o1.getDate() - o2.getDate());
                        }
                    });
                    panelView.getChatArea().setListData(list.toArray(new Object[list.size()]));
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    @Override
    public Container getView() {
        panelView = new ChatPanelView();
        return panelView;
    }

    @Override
    public void refresh() {
        chatMessages = ChatApplicationController.getInstance().getChatMessages();
        MessageResponse response = new MessagesRequest().execute();
        chatMessages.addAll(response.getMessages());
        ArrayList<ChatMessage> list = new ArrayList<ChatMessage>(chatMessages);
        Collections.sort(list, new Comparator<ChatMessage>() {
            public int compare(ChatMessage o1, ChatMessage o2) {
                return (int) (o1.getDate() - o2.getDate());
            }
        });
        panelView.getChatArea().setListData(list.toArray(new Object[list.size()]));
        thread.start();
    }
}
